package com.example.transaction.sys.controller;

import com.example.transaction.common.vo.Result;
import com.example.transaction.sys.service.impl.QiniuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import com.example.transaction.common.vo.Result;
import com.example.transaction.sys.service.impl.QiniuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@RequestMapping("/sys/qiniu")
@Slf4j
public class QiniuController {

    @Autowired
    private QiniuService qiniuService;

    private static final String HTTP_PREFIX = "http://";

    @RequestMapping(value="/uploadImg", method= RequestMethod.POST)
    @PermitAll
    public Result uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Result success = Result.success();

        if(file.isEmpty()) {
            success.setCode(400);
            success.setMessage("文件为空，请重新上传");
            return success;
        }

        try {
            String fileUrl=qiniuService.saveImage(file);
            fileUrl=fileUrl.replace("com","com/");
            success.setCode(200);
            success.setMessage("文件上传成功");
            success.setData(fileUrl);

            return success;
        } catch (IOException e) {
            e.printStackTrace();
        }
        success.setCode(500);
        success.setMessage("文件上传发生异常！");
        return success;
    }
}


